package com.okq.action;
import com.okq.action.base.BaseActionSupport;
import com.okq.entity.*;
import com.okq.service.*;
import com.okq.util.BaseTool;
import com.okq.util.PublicClass;
import com.okq.util.TimeTool;
import com.okq.util.page.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.PrintWriter;
import java.util.*;

/**
 * 描述 : 工单列表
 * 作者 : zdl
 * 日期 : 2017/7/12 9:55
 */
public class JobAction extends BaseActionSupport {
    private static final long serialVersionUID = 8978741529355704312L;

    /**
     */
    @Autowired
    private IJobService jobServiceImpl;
    /**
     * 客户接口
     */
    @Autowired
    private ICustomerService customerServiceImpl;
    /**
     * 数据字典接口
     */
    @Autowired
    private IDictService dictServiceImpl;
    /**
     * 用户接口
     */
    @Autowired
    private IUserService userServiceImpl;
    /**
     * 工单产品接口
     */
    @Autowired
    private IJobProductService jobProductServiceImpl;
    /**
     * 工单产品处理历史接口
     */
    @Autowired
    private IJobProductHistoryService jobProductHistoryServiceImpl;

    /**
     * 系统日志接口
     */
    @Autowired
    private ILogService logServiceImpl;

    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(JobAction.class);
    /**
     * 分页开始条数
     */
    private int iDisplayStart;

    /**
     * 每页显示条数
     */
    private int iDisplayLength;

    private String id;
    private Job job;
    private String type;

    /**
     * 获取工单分页列表
     *
     * @return json
     */
    public String getJobList() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                if (iDisplayLength == 0) {
                    iDisplayLength = -1;
                }
                int pageNum = (int) (Math.ceil(iDisplayStart / iDisplayLength)) + 1;
                /* 分页信息 */
                Page<Job> pageInfo = new Page<>(iDisplayLength);
                pageInfo.setPageNo(pageNum);
                pageInfo = jobServiceImpl.pageByJob(pageInfo, job);
                int iTotalRecords = pageInfo.getTotalCount();
                int iTotalDisplayRecords = pageInfo.getTotalCount() < 0 ? 0 : pageInfo.getTotalCount();
                /* 得到结果 */
                List<Job> jList = pageInfo.getResult();
                /* 封装list */
                List<Map<String, Object>> jobMapList = new ArrayList<>();
                
                if (jList != null && !jList.isEmpty() && jList.size() > 0) {
                    int i = (pageNum - 1) * iDisplayLength + 1;
                    for (Job j : jList) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("no", i);// 序号
                        map.put("id", j.getId());
                        map.put("jobCode", StringUtils.defaultString(j.getCode(), ""));
                        String stateStr = "";
                        Integer state = j.getState();
                        if (state != null) {
                            switch (state) {
                                case 0:
                                    stateStr = "一般";
                                    break;
                                case 1:
                                    stateStr = "正常";
                                    break;
                                case 2:
                                    stateStr = "紧急";
                                    break;
                                default:
                                    break;
                            }
                        }
                        map.put("stateStr", stateStr);
                        String customerId = StringUtils.defaultString(j.getCustomerId(), "");
                        map.put("customerId", customerId);
                        String customerName = "";
                        String customerContact = "";
                        String customerAddress = "";
                        String customerLevel = "";
                        String chargeName = "";
                        if (StringUtils.isNotBlank(customerId)) {
                            Customer c = customerServiceImpl.getCustomerById(customerId);
                            if (c != null) {//userServiceImpl
                                customerName = StringUtils.defaultString(c.getName(), "");
                                customerContact = StringUtils.defaultString(c.getContact(), "");
                                customerAddress = StringUtils.defaultString(c.getAddress(), "");
                                Integer level = c.getLevel();
                                if (level == 1) {
                                    customerLevel = "会员";
                                }else{
                                    customerLevel = "普通";
                                }
                                String chargeId = c.getChargeId();
                                if (StringUtils.isNotBlank(chargeId)) {
                                    User u = userServiceImpl.getUserById(chargeId);
                                    if (u != null) {
                                        chargeName = StringUtils.defaultString(u.getUserName(), "");
                                    }
                                }
                            }
                        }
                        map.put("customerName", customerName);
                        map.put("customerContact", customerContact);
                        map.put("customerAddress", customerAddress);
                        map.put("customerLevel", customerLevel);
                        map.put("chargeName", chargeName);
                        map.put("createUserName", StringUtils.defaultString(j.getCreateUserName(), ""));
                        map.put("createTime", TimeTool.timestampToString(j.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                        jobMapList.add(map);
                        i++;
                    }
                }
                Map<String, Object> jsonMap = new HashMap<>();
                jsonMap.put("iTotalRecords", iTotalRecords);
                jsonMap.put("iTotalDisplayRecords", iTotalDisplayRecords);
                jsonMap.put("aaData", jobMapList);

                String json = BaseTool.toJson(jsonMap);
                out.print(json);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 删除工单
     *
     * @return 成功标识
     */
    public String deleteJob() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                Job j = jobServiceImpl.getJobById(id);
                if (j != null) {
                    j.setIsDelete(1);
                    jobServiceImpl.updateJob(j);
                    List<JobProduct> jpList = jobProductServiceImpl.listJobProductByJid(j.getId());
                    if (jpList != null && !jpList.isEmpty() && jpList.size() > 0) {
                        for (JobProduct jp : jpList) {
                            jp.setIsDelete(1);
                            jp.setUpdateUserId(loginUser.getId());
                            jp.setUpdateUserName(loginUser.getUserName());
                            jobProductServiceImpl.updateJobProduct(jp);
                            List<JobProductHistory> jphList = jobProductHistoryServiceImpl.listJobProductHistoryByJpId(jp.getId());
                            if (jphList != null && !jphList.isEmpty() && jphList.size() > 0) {
                                for (JobProductHistory jph : jphList) {
                                    jph.setIsDelete(1);
                                    jobProductHistoryServiceImpl.updateJobProductHistory(jph);
                                }
                            }
                        }
                    }
                    out.print(0);
                    //添加系统日志
                    String userName = loginUser.getUserName();
                    String nowTime = TimeTool.getNowTime();
                    String content = "用户：" + userName + "，于" + nowTime + " 删除工单：" + j.getCode() + "！";
                    PublicClass.addLog(userName, loginUser.getLoginName(), "工单管理", 2, content, logServiceImpl);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 跳转到修改页面
     *
     * @return type
     */
    public String toUpdate() {
        try {
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                job = jobServiceImpl.getJobById(id);
                if (job != null && type.equals("update")) {
                    return "update";
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return null;
    }

    /**
     * 保存工单
     *
     * @return 成功标识
     */
    public String saveJob() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && job != null) {
                if (StringUtils.isNotBlank(type) && type.equals("add")) {// 新增
                    job.setId(BaseTool.getPK());
                    String jobCode = getJobCode();
                    job.setCode(jobCode);
                    String userName = loginUser.getUserName();
                    if (StringUtils.isNotBlank(userName)) {
                        job.setCreateUserId(loginUser.getId());
                        job.setCreateUserName(userName);
                    }
                    String comCode = loginUser.getComCode();
                    if (StringUtils.isNotBlank(comCode)) {
                        job.setComCode(comCode);
                    }
                    jobServiceImpl.saveJob(job);
                    out.print("success");
                    //添加系统日志
                    String nowTime = TimeTool.getNowTime();
                    String content = "用户：" + userName + "，于" + nowTime + " 添加工单：" + jobCode + "！";
                    PublicClass.addLog(userName, loginUser.getLoginName(), "工单管理", 2, content, logServiceImpl);
                } else if (StringUtils.isNotBlank(type) && type.equals("update")) {// 修改
                    Job oldJob = jobServiceImpl.getJobById(job.getId());
                    if (oldJob != null) {
                        oldJob.setState(job.getState());
                        oldJob.setCustomerId(job.getCustomerId());
                        oldJob.setRemark(job.getRemark());
                        String userName = loginUser.getUserName();
                        if (StringUtils.isNotBlank(userName)) {
                            oldJob.setUpdateUserId(loginUser.getId());
                            oldJob.setUpdateUserName(userName);
                        }
                        jobServiceImpl.updateJob(oldJob);
                        out.print("success");
                        //添加系统日志
                        String nowTime = TimeTool.getNowTime();
                        String content = "用户：" + userName + "，于" + nowTime + " 修改工单：" + oldJob.getCode() + "！";
                        PublicClass.addLog(userName, loginUser.getLoginName(), "工单管理", 2, content, logServiceImpl);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 获取工单编号
     *
     * @return 工单编号
     */
    private String getJobCode() {
        String jobCode = "";
        try {
            Job j = jobServiceImpl.getLastJob();
            if (j != null) {
                String code = j.getCode();
                if (StringUtils.isNotBlank(code)) {
                    String oldCodeDate = code.substring(3, 11);
                    String nowDate = TimeTool.formatDate(new Date(), "yyyyMMdd");
                    if (oldCodeDate.equals(nowDate)) {
                        Integer codeNum = Integer.valueOf(code.substring(11, code.length()));
                        jobCode = code.substring(0, 11) + BaseTool.zeroFormat("000", codeNum + 1);
                    } else {
                        jobCode = getDefaultJobCode();
                    }
                } else {
                    jobCode = getDefaultJobCode();
                }
            } else {
                jobCode = getDefaultJobCode();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return jobCode;
    }

    /**
     * 生成默认工单编号
     *
     * @return 工单编号
     */
    private String getDefaultJobCode() {
        int _suffix = 0;
        String strTmp = TimeTool.formatDate(new Date(), "yyyyMMdd");
        _suffix++;
        if (_suffix > 999) {
            _suffix = 0;
        }
        String jobCode = BaseTool.getPropertiesValue("config.properties", "jobCode");
        if (StringUtils.isBlank(jobCode)) {
            jobCode = "Job";
        }
        strTmp = jobCode + strTmp + String.format("%03d", _suffix);
        return strTmp;
    }

    public int getIDisplayStart() {
        return iDisplayStart;
    }

    public void setIDisplayStart(int iDisplayStart) {
        this.iDisplayStart = iDisplayStart;
    }

    public int getIDisplayLength() {
        return iDisplayLength;
    }

    public void setIDisplayLength(int iDisplayLength) {
        this.iDisplayLength = iDisplayLength;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Job getJob() {
        return job;
    }

    public void setJob(Job job) {
        this.job = job;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}
